import { Injectable, UnauthorizedException } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { LoginDto, LoginResponse, User } from './interfaces/user.interface';
import { AppConfigService } from '../../config/config.service';
import * as bcrypt from 'bcrypt';

@Injectable()
export class AuthService {
  constructor(
    private jwtService: JwtService,
    private configService: AppConfigService,
  ) {}

  private async findUser(username: string): Promise<User | null> {
    // 模拟用户数据，后续替换为数据库查询
    const mockUser: User = {
      id: 1,
      username: 'admin',
      password: await bcrypt.hash('admin123', 10),
      email: 'admin@example.com',
      createdAt: new Date(),
      updatedAt: new Date(),
    };

    return username === mockUser.username ? mockUser : null;
  }

  async validateUser(username: string, password: string): Promise<User> {
    const user = await this.findUser(username);
    if (!user) {
      throw new UnauthorizedException('用户名或密码错误');
    }

    const isValid = await bcrypt.compare(password, user.password);
    if (!isValid) {
      throw new UnauthorizedException('用户名或密码错误');
    }

    return user;
  }

  async login(loginDto: LoginDto): Promise<LoginResponse> {
    const user = await this.validateUser(loginDto.username, loginDto.password);
    const token = await this.jwtService.signAsync({
      sub: user.id,
      username: user.username,
      email: user.email,
    });

    const { password, ...userInfo } = user;
    return {
      token,
      user: userInfo,
    };
  }
}
